# coding=utf-8
import datetime
import json
import os
import telnetlib
import threading
import sys
import getopt


# ip地址数据结构
class IpAddress:
    ipCount = 0
    results = []

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        IpAddress.ipCount += 1

    # 测试ping
    def check_ping(self):
        ans = os.system("ping -c 1 -W 1 {} -p {}".format(self.ip, self.port))
        if ans == 0:
            return True
        return False

    # 测试telnet
    def check_telnet(self):
        try:
            tn = telnetlib.Telnet(self.ip, self.port, timeout=1)
            tn.close()
            # close
        except Exception as err:
            return False
        else:
            return True

    # 整体测试 测试逻辑：ping不通过再测试telnet
    def check(self):
        if self.check_ping():
            if printAll:
                IpAddress.results.append("ip地址{}，端口{}，ping通，telnet通\n".format(self.ip, self.port))
        elif self.check_telnet():
            IpAddress.results.append("ip地址{}，端口{}，ping不通，telnet通过\n".format(self.ip, self.port))
        else:
            IpAddress.results.append("ip地址{}，端口{}，ping不通，telnet不通\n".format(self.ip, self.port))


# 读取参数
inputFilePath = './ipAddress.json'
outputFilePath = './ans.txt'
threadNum = 1  # 线程数
defaultPort = 8080  # 默认端口
printAll = False  # 是否全部输出，否的话只输出报错的
try:
    opts, args = getopt.getopt(sys.argv[1:], "an:p:i:o:", ["all", "number=", "port=", "infile=", "outfile"])
except getopt.GetoptError:
    print("python main.py -n <线程数> -p <默认端口> -f <文件路径> -a")

for opt, arg in opts:
    if opt in ("-a", "all"):
        printAll = True
    elif opt in ("-n", "number"):
        threadNum = int(arg)
    elif opt in ("-p", "port"):
        defaultPort = arg
    elif opt in ("-i", "infile"):
        inputFilePath = arg
    elif opt in ("-o", "outfile"):
        outputFilePath = arg
# 读取ip地址列表
ipList = []
with open(inputFilePath, 'r') as f:
    items = json.load(f)
    for item in items:
        a = IpAddress(item['ip'], item['port'])
        if item['port'] == "":  # 如果没有给ip地址就设置成默认的
            a.port = str(defaultPort)
        ipList.append(a)
    print(IpAddress.ipCount)

# 设置的线程数量超过ip地址数量的时候，线程数改成ip地址数量
threadNum = min(threadNum, len(ipList))


# 一个线程干的事情
def process_list(start, stop):
    for j in range(start, stop):
        ipList[j].check()


# 多线程
threads = []
step = len(ipList) // threadNum
print(step)
for i in range(0, len(ipList), step):
    if i + 2 * step > len(ipList):
        threads.append(threading.Thread(target=process_list, args=(i, len(ipList))))
        break
    threads.append(threading.Thread(target=process_list, args=(i, i + step)))

for thread in threads:
    thread.setDaemon(True)
    thread.start()
for thread in threads:
    thread.join()
print('ok')
# print(IpAddress.results)

# 输出结果
with open(outputFilePath, 'a') as f:
    f.write('[{}]\n'.format(datetime.datetime.now()))
    for result in IpAddress.results:
        f.write(result)
    f.write('\n')
